using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using GameFramework.net;
using GameFramework.net.nettest;
using UnityEngine;
using Object = System.Object;

public class TcpServer
{
    public String ip = "127.0.0.1";
    
    private Socket serverSocket;
    
    // Start is called before the first frame update
    public void Start()
    {
        //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
        try
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipRef = IPAddress.Parse(ip);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 7777);
            // IPEndPoint point = new IPEndPoint(ipRef, port);   //创建对象端口
        
            serverSocket.Bind(ipe);
            serverSocket.Listen(10);
            Debug.Log("服务器已启动，端口："+7777);
            TcpServeStatusChange serverStatusChange = new TcpServeStatusChange();
            serverStatusChange.status = 1;
            serverStatusChange.msg = "启动成功！";
            EventManager.Instance.dispatchAsync(serverStatusChange);
            
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                IPEndPoint remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
                Debug.Log("连接成功 , " +  remoteEndPoint.Address.MapToIPv4() );
                NetManager.Instance.addClient(new Client(clientSocket,"")); 
            }

        }
        catch (Exception e)
        {
            TcpServeStatusChange serverStatusChange = new TcpServeStatusChange();
            serverStatusChange.status = 2; 
            serverStatusChange.msg = e.GetBaseException().Message;
            EventManager.Instance.dispatchAsync(serverStatusChange);
            Debug.LogError(e);
        }


    }
}
